package org.example.controller;

import org.example.model.Message;
import org.example.service.RabbitMQMessageService;
import org.example.service.RedisSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    @Autowired
    private RabbitMQMessageService rabbitMQMessageService;

    @Autowired
    private RedisSessionService redisSessionService;

    @MessageMapping("/chat.send")
    @SendToUser("/queue/messages")
    public Message sendMessage(@Payload Message message, SimpMessageHeaderAccessor headerAccessor) {
        String userId = getUserIdFromHeader(headerAccessor);
        logger.info("收到来自用户 {} 的消息: {}", userId, message.getContent());
        
        // 存储消息到Redis或数据库
        // 通过RabbitMQ转发到其他服务器
        if (message.getTargetUserId() != null) {
            rabbitMQMessageService.sendMessageToUser(message.getTargetUserId(), message);
        }
        
        return message;
    }

    @MessageMapping("/chat.heartbeat")
    @SendToUser("/queue/heartbeat")
    public String handleHeartbeat(SimpMessageHeaderAccessor headerAccessor) {
        String userId = getUserIdFromHeader(headerAccessor);
        if (userId != null) {
            redisSessionService.updateHeartbeat(userId);
            logger.debug("用户 {} 心跳检测", userId);
            return "HEARTBEAT_ACK";
        }
        return "HEARTBEAT_FAILED";
    }

    @MessageMapping("/chat.broadcast")
    public void broadcastMessage(@Payload Message message, SimpMessageHeaderAccessor headerAccessor) {
        String userId = getUserIdFromHeader(headerAccessor);
        logger.info("用户 {} 发起广播消息: {}", userId, message.getContent());
        
        rabbitMQMessageService.broadcastMessage(message);
    }

    private String getUserIdFromHeader(SimpMessageHeaderAccessor headerAccessor) {
        if (headerAccessor != null && headerAccessor.getUser() != null) {
            return headerAccessor.getUser().getName();
        }
        return null;
    }
}